const express = require('express');
const router = express.Router();
const { getDB } = require('../db/database');

const db = getDB();

// 获取帖子列表（分页）
router.get('/', (req, res) => {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 20;
    const offset = (page - 1) * limit;

    const query = `
        SELECT id, content, likes, created_at 
        FROM posts 
        ORDER BY created_at DESC 
        LIMIT ? OFFSET ?
    `;

    db.all(query, [limit, offset], (err, rows) => {
        if (err) {
            res.status(500).json({ error: '获取帖子失败' });
            return;
        }
        res.json(rows);
    });
});

// 创建新帖子
router.post('/', (req, res) => {
    const { content } = req.body;

    if (!content || content.trim().length === 0) {
        res.status(400).json({ error: '内容不能为空' });
        return;
    }

    if (content.length > 500) {
        res.status(400).json({ error: '内容不能超过500字' });
        return;
    }

    const query = 'INSERT INTO posts (content) VALUES (?)';
    
    db.run(query, [content.trim()], function(err) {
        if (err) {
            res.status(500).json({ error: '发布失败' });
            return;
        }
        
        res.json({ 
            id: this.lastID, 
            content: content.trim(), 
            likes: 0, 
            created_at: new Date().toISOString() 
        });
    });
});

// 点赞
router.post('/:id/like', (req, res) => {
    const postId = parseInt(req.params.id);
    
    if (isNaN(postId)) {
        res.status(400).json({ error: '无效的帖子ID' });
        return;
    }

    const query = 'UPDATE posts SET likes = likes + 1 WHERE id = ?';
    
    db.run(query, [postId], function(err) {
        if (err) {
            res.status(500).json({ error: '点赞失败' });
            return;
        }
        
        if (this.changes === 0) {
            res.status(404).json({ error: '帖子不存在' });
            return;
        }
        
        // 返回更新后的点赞数
        db.get('SELECT likes FROM posts WHERE id = ?', [postId], (err, row) => {
            if (err) {
                res.status(500).json({ error: '获取点赞数失败' });
                return;
            }
            res.json({ likes: row.likes });
        });
    });
});

module.exports = router;
